package cn.sq.musicserver.scheduling.job.job;

import cn.sq.musicserver.music.entity.SqMusic;
import cn.sq.musicserver.music.service.impl.SqMusicServiceImpl;
import cn.sq.musicserver.plug.entity.PlugLyicResult;
import cn.sq.musicserver.plug.entity.PlugSearchResult;
import cn.sq.musicserver.plug.model.jsososo.JsososoHander;
import cn.sq.musicserver.plug.model.jsososo.entity.LyircResult;
import cn.sq.musicserver.plug.model.jsososo.entity.LyricParam;
import cn.sq.musicserver.plug.model.qqmusicapi.QQMusicApiHander;
import cn.sq.musicserver.set.entity.SqSet;
import cn.sq.musicserver.set.service.impl.SqSetServiceImpl;
import cn.sq.musicserver.utils.FileUtil;
import cn.sq.musicserver.utils.MuiscUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.io.File;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: SQ
 * Date: 2020/12/28
 * Time: 16:02
 * Description: 本地音乐扫描
 */
@Component
@Slf4j
public class MuiscScanJob extends QuartzJobBean {
    @Autowired
    SqSetServiceImpl setService;
    @Autowired
    SqMusicServiceImpl musicService;
    @Autowired
    QQMusicApiHander qqMusicApiHander;
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.debug("开始扫描文件夹");
        SqSet SystemScanDir = setService.getOne(new QueryWrapper<SqSet>().eq("SetName", "SystemScanDir"));
        SqSet SystemDownloadDir = setService.getOne(new QueryWrapper<SqSet>().eq("SetName", "SystemDownloadDir"));
        SqSet SystemScanFileNameType = setService.getOne(new QueryWrapper<SqSet>().eq("SetName", "SystemScanFileNameType"));
        SqSet SystemDownloadFileNameType = setService.getOne(new QueryWrapper<SqSet>().eq("SetName", "SystemDownloadFileNameType"));
        SqSet SystemScanType_p = setService.getOne(new QueryWrapper<SqSet>().eq("SetName", "SystemScanType_p"));
        SqSet SystemImageDir = setService.getOne(new QueryWrapper<SqSet>().eq("SetName", "SystemImageDir"));
        HashMap<String, String> map = new HashMap<>();
        map.put("type_p", SystemScanType_p.getSetVlaue());
        //歌手名称在第几位默认是  歌曲名称-歌手
        int scanMusicNameIndex = 0;
        int scanArtistindex = 1;
        if (!SystemScanFileNameType.getSetVlaue().equals("1")) {
            scanMusicNameIndex = 1;
            scanArtistindex = 0;
        }
        Collection<File> files = FileUtils.listFiles(new File(SystemScanDir.getSetVlaue()), MuiscUtils.MsicExtensions(), false);
        for (File iteam : files) {
            String name = iteam.getName();
            log.debug("扫描歌曲"+name);
            String musicname = null;
            String artist = null;
            String fileSuffix = FileUtil.getFileSuffix(name);
            name = name.replaceAll(fileSuffix,"");
            try {
                String[] split = name.toLowerCase().split("-");
                musicname = split[scanMusicNameIndex];
                artist = split[scanArtistindex];
            } catch (Exception e) {
                musicname=name;
                artist="";
            }


            PlugSearchResult plugSearchResult = null;
            try {
                plugSearchResult = qqMusicApiHander.musicInfoSearc(1, 1, musicname + " " + artist, null, null, map);
                //解析歌曲信息
                PlugSearchResult.Song song = plugSearchResult.getSongs().get(0);
                PlugLyicResult qq = qqMusicApiHander.MusiclyricDownload(new LyricParam().setId(song.getId()).setType_p("qq"));
                SqMusic sqMusic = new SqMusic().setMusicAlbum(song.getMusicAlbum())
                        .setMusicArtists(song.getMusicArtists())
                        .setMusicName(song.getMusicName())
                        .setMusicType("扫描")
                        .setMusicCodeType(fileSuffix.replaceAll(".",""))
                        .setMusicLyric(qq.getLyric())
                        .setMusicLyricTrans(qq.getTrans())
                        .setMusicSourImageUrl(song.getMusicImage())
                        .setMusicImage(FileUtil.downloadToFile(song.getMusicImage(), SystemImageDir.getSetVlaue()))
                        .setMusicTime(LocalDateTime.now())
                        .setMusicPath(iteam.getName());
                boolean save = musicService.save(sqMusic);
                if (!save) {
                    new Exception("保存数据失败");
                }

                String downloadName;
                if (SystemDownloadFileNameType.getSetVlaue().equals("1")) {
                    downloadName = musicname + "-" + artist;
                } else {
                    downloadName = musicname + "-" + artist;
                }
                FileUtils.moveFile(iteam, new File(SystemDownloadDir.getSetVlaue() + "/" + downloadName + FileUtil.getFileSuffix(iteam.getName())));
                log.debug("扫描完成歌曲"+name);
                //拷贝至下载模具
            } catch (Exception e) {
                log.error("扫描歌曲错误： ");
                log.error("错误信息：" + e.getMessage());
            }
        }
    }
}
